﻿#encoding:utf-8
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_unicode

register = template.Library()

def truncate_zhwords(s, num):
    s = force_unicode(s)
    length = int(num)
    if len(s) > length*2:
        s = s[:length*2]
        s += u'……'
    return u' '.join(s)

@register.filter
@stringfilter
def zhwordstruncate(value, arg):
    try:
        length = int(arg)
    except ValueError: # Invalid literal for int().
        return value # Fail silently.
    return truncate_zhwords(value, length)

